const express = require('express');
const OSS = require('ali-oss');
require('dotenv').config();
const { pool, initializeDatabase } = require('./db');



const path = require('path'); // 引入 path 模块，用于处理文件路径

//---------------------------------------------------------

// 应该放在 API 路由定义之前。
const app = express();
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));

// OSS客户端配置
const client = new OSS({
  region: process.env.OSS_REGION,
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  bucket: process.env.OSS_BUCKET,
});

(async () => {
  try {
    await initializeDatabase();
  } catch (error) {
    console.error('初始化数据库失败:', error);
    process.exit(1);
  }
})();

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*'); // 或 '*' 允许所有
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  next();
});

// 生成上传用的预签名URL
app.get('/api/upload-url', async (req, res) => {
  try {
    console.log(req.query);
    const { filename, contentType } = req.query;
    if (!filename || !contentType) {
      return res.status(400).json({ error: '文件名和内容类型是必需的' });
    }

    // 生成唯一文件名
    const key = `uploads/${Date.now()}-${filename}`;
    
    // 生成预签名URL，有效期1小时
    const url = client.signatureUrl(key, {
      method: 'PUT',
      expires: 7200,
      'Content-Type': contentType
    });
    console.log(url);
    res.json({ 
      uploadUrl: url,
      fileKey: key,
      expiresIn: 3600
    });
  } catch (error) {
    console.error('生成预签名URL失败:', error);
    res.status(500).json({ error: '生成预签名URL失败' });
  }
});
app.post('/api/reviews',async (req, res) => {
  try {
    const {
    userId,
    userName,
    restaurantName,
    restaurantLocation,
    dishName,
    rating,
    reviewText,
    imageKeys
  } = req.body;

  console.log('收到的数据:', {
    userId,
    userName,
    restaurantName,
    restaurantLocation,
    dishName,
    rating,
    reviewText,
    imageKeys
  });
  const [result] = await pool.query(
      'INSERT INTO review (student_id,name,restaurant_name,restaurant_location,recommend_menu,score,description,image) VALUES (' +
    	'?,?,?,?,?,?,?,?)',
      [userId,userName,restaurantName,restaurantLocation,dishName,rating,reviewText,imageKeys]
   );
   console.log(res)
   res.status(200).json({ok:true,
   			id:userId});
  } catch (error) {
    console.error('提交评价失败:', error);
    res.status(500).json({ error: '提交评价失败' });
  }	

})

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
});
